package cn.csc.module.shoppingCard.controller.admin.transaction;

import cn.csc.framework.common.pojo.CommonResult;
import cn.csc.framework.common.pojo.PageResult;
import cn.csc.framework.common.util.collection.CollectionUtils;
import cn.csc.framework.common.util.json.JsonUtils;
import cn.csc.framework.excel.core.util.ExcelUtils;
import cn.csc.framework.operatelog.core.annotations.OperateLog;
import cn.csc.module.order.api.item.OrderItemApi;
import cn.csc.module.order.api.item.dto.OrderItemRespDTO;
import cn.csc.module.order.enums.OrderItemOrderStatusEnum;
import cn.csc.module.shoppingCard.controller.admin.transaction.vo.*;
import cn.csc.module.shoppingCard.convert.transaction.CardTransactionConvert;
import cn.csc.module.shoppingCard.dal.dataobject.transaction.CardTransactionDO;
import cn.csc.module.shoppingCard.enums.TradeTypeEnum;
import cn.csc.module.shoppingCard.service.transaction.CardTransactionService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.csc.framework.common.pojo.CommonResult.success;
import static cn.csc.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;

@Api(tags = "管理后台 - 交易记录")
@RestController
@RequestMapping("/shoppingCard/card-transaction")
@Validated
@Slf4j
public class CardTransactionController {

    @Resource
    private CardTransactionService cardTransactionService;

    @Resource
    private OrderItemApi orderItemApi;

    @PostMapping("/create")
    @ApiOperation("创建交易记录")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:create')")
    public CommonResult<BigInteger> createCardTransaction(@Valid @RequestBody CardTransactionCreateReqVO createReqVO) {
        return success(cardTransactionService.createCardTransaction(createReqVO));
    }

    @PutMapping("/update")
    @ApiOperation("更新交易记录")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:update')")
    public CommonResult<Boolean> updateCardTransaction(@Valid @RequestBody CardTransactionUpdateReqVO updateReqVO) {
        cardTransactionService.updateCardTransaction(updateReqVO);
        return success(true);
    }

    @DeleteMapping("/delete")
    @ApiOperation("删除交易记录")
    @ApiImplicitParam(name = "id", value = "编号", required = true, dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:delete')")
    public CommonResult<Boolean> deleteCardTransaction(@RequestParam("id") BigInteger id) {
        cardTransactionService.deleteCardTransaction(id);
        return success(true);
    }

    @GetMapping("/get")
    @ApiOperation("获得交易记录")
    @ApiImplicitParam(name = "id", value = "编号", required = true, example = "1024", dataTypeClass = BigInteger.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:query')")
    public CommonResult<CardTransactionRespVO> getCardTransaction(@RequestParam("id") BigInteger id) {
        CardTransactionDO cardTransaction = cardTransactionService.getCardTransaction(id);
        return success(CardTransactionConvert.INSTANCE.convert(cardTransaction));
    }

    @GetMapping("/list")
    @ApiOperation("获得交易记录列表")
    @ApiImplicitParam(name = "ids", value = "编号列表", required = true, example = "1024,2048", dataTypeClass = List.class)
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:query')")
    public CommonResult<List<CardTransactionRespVO>> getCardTransactionList(@RequestParam("ids") List<BigInteger> ids) {
        List<CardTransactionDO> list = cardTransactionService.getCardTransactionList(ids);
        return success(CardTransactionConvert.INSTANCE.convertList(list));
    }

    @GetMapping("/page")
    @ApiOperation("获得交易记录分页")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:query')")
    public CommonResult<PageResult<CardTransactionRespVO>> getCardTransactionPage(@Valid CardTransactionPageReqVO pageVO) {
        PageResult<CardTransactionDO> pageResult = cardTransactionService.getCardTransactionPage(pageVO);
        PageResult<CardTransactionRespVO> convertPage = CardTransactionConvert.INSTANCE.convertPage(pageResult);
        if (CollectionUtils.isAnyEmpty(convertPage.getList())){
            return success(convertPage);
        }
        List<CardTransactionRespVO> list = convertPage.getList();
        List<BigInteger> itemIds = list.stream().map(CardTransactionRespVO::getRelatedOrderItem).collect(Collectors.toList());
        List<OrderItemRespDTO> respDTOS = orderItemApi.getByIds(itemIds).getCheckedData();
        Map<BigInteger, OrderItemRespDTO> dtoMap = CollectionUtils.convertMap(respDTOS, OrderItemRespDTO::getId);
        list.forEach(ct -> ct.setOrderItem(dtoMap.get(ct.getRelatedOrderItem())));
        return success(convertPage);
    }

    @GetMapping("/export-excel")
    @ApiOperation("导出交易记录 Excel")
    @PreAuthorize("@ss.hasPermission('shoppingCard:card-transaction:export')")
    @OperateLog(type = EXPORT)
    public void exportCardTransactionExcel(@Valid CardTransactionExportReqVO exportReqVO,
              HttpServletResponse response) throws IOException {
        List<CardTransactionDO> list = cardTransactionService.getCardTransactionList(exportReqVO);
        log.info("exportCardTransactionExcel list: {}", JsonUtils.toJsonString(list));
        // 导出 Excel
        List<CardTransactionExcelVO> datas = CardTransactionConvert.INSTANCE.convertList02(list);
        if (!CollectionUtils.isAnyEmpty(datas)){
            List<BigInteger> itemIds = list.stream().map(CardTransactionDO::getRelatedOrderItem).collect(Collectors.toList());
            List<OrderItemRespDTO> respDTOS = orderItemApi.getByIds(itemIds).getCheckedData();
            // CardTransactionExcelVO中relatedOrderItem定义为String类型
            Map<String, OrderItemRespDTO> dtoMap = CollectionUtils.convertMap(respDTOS, (k) -> String.valueOf(k.getId()));
            datas.forEach(ct -> {
                ct.setTxnType(TradeTypeEnum.getByType(Integer.valueOf(ct.getTxnType())).getName());
                ct.setShopName(dtoMap.get(ct.getRelatedOrderItem()).getShopName());
                ct.setUserId(String.valueOf(dtoMap.get(ct.getRelatedOrderItem()).getUserId()));
                ct.setSpuName(dtoMap.get(ct.getRelatedOrderItem()).getSpuName());
                ct.setSkuName(dtoMap.get(ct.getRelatedOrderItem()).getSkuName());
                ct.setFreightRemark(dtoMap.get(ct.getRelatedOrderItem()).getFreightRemark());
                ct.setSpuTotalAmount(dtoMap.get(ct.getRelatedOrderItem()).getSpuTotalAmount());
                ct.setSpuActualAmount(dtoMap.get(ct.getRelatedOrderItem()).getSpuActualAmount());
                ct.setCardPayAmount(dtoMap.get(ct.getRelatedOrderItem()).getCardPayAmount());
                // 订单状态 0未付款,1已付款,2已发货,3已签收,-1退货申请,-2退货中,-3已退货,-4取消交易 -5撤销申请
                ct.setOrderStatus(OrderItemOrderStatusEnum.getByStatus(dtoMap.get(ct.getRelatedOrderItem()).getOrderStatus()).getName());
                ct.setMemberPhone(dtoMap.get(ct.getRelatedOrderItem()).getMemberPhone());
            });
        }
        ExcelUtils.write(response, "交易记录.xls", "数据", CardTransactionExcelVO.class, datas);
    }

}
